package cn.uway.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;


public class HttpFileUtils {

	//web 应用的接口秘钥
	private static final String appId="67d307e4d1d143d6acd6a33a87d367b9";
	private static final String secretKey="55f2bfde6cd64f00acd2294bbd0963f4";
		
    //连接超时时间，默认30秒
    private static int connectTimeout = 30*1000;
    
    //数据传输超时时间，默认30秒
    private static int socketTimeout = 30*1000;
    
    private static final String	boundary = 	"------WebKitFormBoundaryWbXaRVMLf0KDg7bP";    
     
    public  static  String  uploadFile(String actionUrl, String folderName, String fileName, InputStream in) {
    	
		DataOutputStream out =  null;
		BufferedReader reader = null;
		String param = "folderName="+folderName;
		if(!param.contains("appId=")){
			if("".equals(param.trim())){
				param = "appId="+appId;
			}
			else{
				param += "&appId="+appId;
			}			
		}
		String sign = getSignString(param);
		Map<String,String> parameterMap = new HashMap<String,String>();
		parameterMap.put("appId", appId);
		parameterMap.put("folderName", folderName);
		parameterMap.put("sign", sign);
		HttpURLConnection conn = null;
		try {
			URL url = new URL(actionUrl);
			conn = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(connectTimeout);
			conn.setReadTimeout(socketTimeout);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type",	"multipart/form-data;boundary=" + boundary);
			/* 设置DataOutputStream */
			out = new DataOutputStream(conn.getOutputStream());
			
			printFormParameters( out,  parameterMap);
			
			printFileData( out,  in,  fileName);
			
			out.flush();
			
			/* 取得Response内容 */
			StringBuffer sb = new StringBuffer();
			reader = new BufferedReader( new InputStreamReader(conn.getInputStream() , "utf-8" ) );
            String line;
            while ((line = reader.readLine()) != null) {
               sb.append(line);
            }
            return sb.toString();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(reader!=null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(conn!=null){
				conn.disconnect();
			}
		}
		return null;
	}
    
    private static void  printFormParameters(DataOutputStream out, Map<String,String> parameterMap) throws IOException{
    	Iterator<String> it = parameterMap.keySet().iterator();
    	while (it.hasNext()) {
			String key = it.next();
			String val = parameterMap.get(key);    			
			out.writeBytes("--" + boundary + "\r\n");  
            out.writeBytes("Content-Disposition: form-data; name=\""+key+"\"");             
            out.writeBytes("\r\n\r\n");  
            out.writeBytes(val);
			out.writeBytes("\r\n");    					
    	}    	
    }
    
    private static void  printFileData(DataOutputStream out, InputStream in, String fileName) throws IOException{
    	out.writeBytes("--" + boundary + "\r\n");  
		out.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""+URLEncoder.encode(fileName, "UTF-8")+"\"\r\n");  
		out.writeBytes("Content-Type: application/octet-stream\r\n");
		out.writeBytes("\r\n");	
		
		/* 设置每次写入8192bytes */
		byte[] buffer = new byte[8192];
		int readLen = 0;
		/* 从文件读取数据至缓冲区 */
		while ((readLen = in.read(buffer)) != -1) {
			out.write(buffer, 0, readLen);
		}		
		out.writeBytes("\r\n");
		out.writeBytes("--" + boundary + "--" + "\r\n");  
		out.writeBytes("\r\n");
    }
    
    public static  String  getSignString(String parameterString){
		if(parameterString.startsWith("?")){
			parameterString = parameterString.substring(1); //去掉开头的问号
		}
		String[] params = parameterString.split("&");
		Map<String, String> paramTreeMap = new TreeMap<String, String>();
		for(String parameter : params){
			int pos = parameter.indexOf("=");
			String key = parameter.substring(0,pos);
			String val = parameter.substring(pos+1);
			if(key!=null && !"".endsWith(key.trim()) && !"sign".equals(key)){
				if(val!=null && !"".equals(val.trim())){
					paramTreeMap.put(key, val);
				}				
			}
		}
		
		StringBuilder sb = new StringBuilder();
    	Iterator<String> iter = paramTreeMap.keySet().iterator();
		while (iter.hasNext()) {
			String name = (String) iter.next();
			sb.append(name).append(paramTreeMap.get(name));
		}
		sb.append(secretKey);
		return MD5Encoder.encode(sb.toString());
	}	
    
    public static void main(String[] args){	  
    	String url ="http://192.168.0.226:8080/fileService/v1/file/upload";
    	String folderName = "test";
    	InputStream in = null;
    	String fileName = "backdround-img.png";
		try {
			in = new FileInputStream("d:/backdround-img.png");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
    	String  json = uploadFile(url,folderName, fileName, in );
    	System.out.println(json);
    }
    
    
}
